package com.ruoyi.consumer.controller;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.consumer.domain.CCompany;
import com.ruoyi.consumer.domain.CUser;
import com.ruoyi.consumer.domain.param.UserQueryParam;
import com.ruoyi.consumer.service.ICCompanyService;
import com.ruoyi.consumer.service.ICUserService;
import com.ruoyi.consumer.service.impl.CompanyBindServiceImpl;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import io.jsonwebtoken.lang.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户账号Controller
 * 
 * @author ruoyi
 * @date 2023-10-10
 */
@RestController
@RequestMapping("/consumer/user")
public class CUserController extends BaseController
{
    @Autowired
    private ICUserService cUserService;

    @Autowired
    private ICCompanyService cCompanyService;

    @Autowired
    private SysUserServiceImpl sysUserService;

    @Autowired
    private CompanyBindServiceImpl companyBindService;

    @Autowired
    private RedisCache redisCache;
    public TableDataInfo getDataTable(List<CUser> list, List<?> list1)
    {
        // 使用原始 list 创建 PageInfo 对象来保留分页信息
        PageInfo<CUser> pageInfo = new PageInfo<>(list);
        TableDataInfo rspData = new TableDataInfo(list1, (int)pageInfo.getTotal());
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list1);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }


    /**
     * 查询用户账号列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CUser cUser)
    {
        Long userAdminId = SecurityUtils.getUserId();
        SysUser sysUser = sysUserService.selectUserById(userAdminId);
        Assert.notNull(sysUser, "用户不存在");


        if (userAdminId != 1) {
            CCompany company = new CCompany();
            company.setCompanDept(Math.toIntExact(sysUser.getDeptId()));
            List<CCompany> cCompany = cCompanyService.selectCCompanyList(company);
            if (cCompany.isEmpty()) {
                return null;
            }else {
                cUser.setCompanyId(cCompany.get(0).getCompanyId());
            }

        }

        startPage();
        List<CUser> list = cUserService.selectCUserList(cUser);
        System.out.println(list);
        List<UserQueryParam> userQueryParams = new ArrayList<>();
        for (CUser user : list) {
            UserQueryParam userQueryParam = new UserQueryParam();
            userQueryParam.setUserId(user.getUserId());
            userQueryParam.setUserPhone(user.getUserPhone());
            userQueryParam.setUserNick(user.getUserNick());
            userQueryParam.setUserHeader(user.getUserHeader());
            userQueryParam.setUserName(user.getUserName());
            userQueryParam.setUserRole(user.getUserRole());
            CCompany cCompany = cCompanyService.selectCCompanyByCompanyId(user.getCompanyId());
            if (cCompany != null)
                userQueryParam.setCompanyName(cCompany.getCompanyName());
            else
                userQueryParam.setCompanyName("暂未绑定公司");
            userQueryParams.add(userQueryParam);
        }
        return getDataTable(list,userQueryParams);
    }

    @GetMapping("/admin-list")
    public TableDataInfo adminList(CUser cUser)
    {
        startPage();
        List<CUser> list = cUserService.selectCUserList(cUser);
        List<UserQueryParam> userQueryParams = new ArrayList<>();
        for (CUser user : list) {
            UserQueryParam userQueryParam = new UserQueryParam();
            userQueryParam.setUserId(user.getUserId());
            userQueryParam.setUserPhone(user.getUserPhone());
            userQueryParam.setUserNick(user.getUserNick());
            userQueryParam.setUserHeader(user.getUserHeader());
            userQueryParam.setUserName(user.getUserName());
            userQueryParam.setUserRole(user.getUserRole());
            String companyName = cCompanyService.selectCCompanyByCompanyId(user.getCompanyId()) == null? null : cCompanyService.selectCCompanyByCompanyId(user.getCompanyId()).getCompanyName();
            if (companyName != null)
                userQueryParam.setCompanyName(companyName);
            else
                userQueryParam.setCompanyName("暂未绑定公司");
            userQueryParams.add(userQueryParam);
        }
        return getDataTable(list,userQueryParams);
    }

    /**
     * 导出用户账号列表
     */
    @Log(title = "用户账号", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CUser cUser)
    {
        List<CUser> list = cUserService.selectCUserList(cUser);
        ExcelUtil<CUser> util = new ExcelUtil<CUser>(CUser.class);
        util.exportExcel(response, list, "用户账号数据");
    }

    /**
     * 获取用户账号详细信息
     */
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Integer userId)
    {
        return success(cUserService.selectCUserByUserId(userId));
    }

    /**
     * 新增用户账号
     */
    @PreAuthorize("@ss.hasPermi('consumer:user:add')")
    @Log(title = "用户账号", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CUser cUser)
    {
        return toAjax(cUserService.insertCUser(cUser));
    }

    /**
     * 修改用户账号
     */
    @Log(title = "用户账号", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CUser cUser)
    {
        return toAjax(cUserService.updateCUser(cUser));
    }

    /**
     * 删除用户账号
     */
    @PreAuthorize("@ss.hasPermi('consumer:user:remove')")
    @Log(title = "用户账号", businessType = BusinessType.DELETE)
	@DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Integer[] userIds)
    {
        return toAjax(cUserService.deleteCUserByUserIds(userIds));
    }
}
